package common

import (
	"encoding/json"
	"net/http"
)

// ControllerInterface 控制器接口
type ControllerInterface interface {
	Success(w http.ResponseWriter, data interface{})
	Error(w http.ResponseWriter, code int, msg string)
	JSON(w http.ResponseWriter, data interface{})
	Render(w http.ResponseWriter, viewPath string, data map[string]interface{})
}

// Controller 控制器基类
type Controller struct {
}

// Success 返回成功响应
func (c *Controller) Success(w http.ResponseWriter, data interface{}) {
	response := map[string]interface{}{
		"code": 0,
		"msg":  "success",
		"data": data,
	}
	c.JSON(w, response)
}

// Error 返回错误响应
func (c *Controller) Error(w http.ResponseWriter, code int, msg string) {
	response := map[string]interface{}{
		"code": code,
		"msg":  msg,
	}
	c.JSON(w, response)
}

// JSON 返回JSON响应
func (c *Controller) JSON(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	encoder := json.NewEncoder(w)
	encoder.Encode(data)
}

// Render 渲染视图
func (c *Controller) Render(w http.ResponseWriter, viewPath string, data map[string]interface{}) {
	// 简化版本的视图渲染，实际项目中可以使用模板引擎
	w.Write([]byte("View: " + viewPath))
}